import React,{useState,useEffect} from 'react';
import {Form,message} from 'antd';
import actions from "../../../../store/actions";
import Cookie from 'react-cookies';
import request from "../../../../assets/js/pc/utils/request";

function hoc (WithComponent){
    return function useHocComponent(props){
        const [form] = Form.useForm();
        // const [, forceUpdate] = useState({}); // 开始提交时禁用按钮
        const [clientId] = useState('ed08944534132f25fba290b355da46ce85f7a522d33f6b44f8182169fedbe1aa');
        const [clientSecret] = useState('c228e9b2251c84b37348436916a8c50ea463486da349fa3fb007ce93259b4187');
        const [redirectUri] = useState('https://houyafei.gitee.io/gatmgr/login');
        const [isLoading,setIsLoading] = useState(false);
        const [isDisabled,setIsDisabled] = useState(true);
        //登录提交
         const onFinish =  (values)=> {
             let data ={
                cellphone:values.username,
                password:values.password,
            }
             setIsLoading(true);
             setIsDisabled(true);
             props.dispatch(actions.actLogin.actLogin({
                 data,
                 success: (res)=>{
                     if (res.code===200){
                         setIsLoading(false);
                         setIsDisabled(false);
                         Cookie.save('access_token',res.data.auth_token)
                         Cookie.save('loginType','login')
                         props.history.replace(window.base.config.path+'personal')
                     }else {
                         message.error({
                             content: res.data,
                             style: {
                                 marginTop: '50vh',
                             },
                         }).then(() => {
                             setIsLoading(false);
                             setIsDisabled(false);
                         })
                     }
                 }
             }))
        };
         //自定义验证
        const handleCheckPwd = (v,rule, value)=>{
            setIsDisabled(false)
            switch (v){
                case 'username':
                    try {
                        let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
                        if (value&&!reg.test(value)) {
                            return Promise.reject("请输入正确的手机号");
                        }
                    } catch (errInfo) {}
                    return Promise.resolve()
                case 'password':
                    return Promise.resolve()
                default:
                    return Promise.resolve()
            }
        }
        //第三方登录
        const thirdLogin = (thirdLoginType)=>{
            switch (thirdLoginType){
                case 'gite':
                    let  url=`${window.base.config.baseUrlGite}oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&response_type=code`;
                    Cookie.save('loginType',thirdLoginType)
                    window.location.href = url;//跳转第三方登录接口并返回code码
                    return ;
                default :
                    return null;
            }
        }
        //跳转页面
        const goPage = (url) =>{
            props.history.replace(window.base.config.path+url)
        }
        useEffect(()=>{
            //拿到code码兑换access_token
            const getAccessToken = ()=>{
                let loginType = Cookie.load('loginType');
                if (loginType !== undefined){
                    let url = window.location.href; //获取当前连接
                    let hasCode = url.includes('?code=')//查看当前链接是否包含code
                    if (hasCode){
                        let newUrl = url.split("?code="); //已?code=临界线分割链接为数组
                        window.history.replaceState({}, null,newUrl[0]) //只修改链接不刷新页面
                        switch (loginType){
                            case 'gite':
                                let url=`${window.base.config.baseUrlGite}oauth/token?grant_type=authorization_code&code=${newUrl[1]}&client_id=${clientId}&redirect_uri=${redirectUri}&client_secret=${clientSecret}`;
                                request(url,'post').then((res)=>{
                                    Cookie.save('access_token',res.access_token);
                                    Cookie.save('refresh_token',res.refresh_token);
                                    props.history.replace(window.base.config.path+'personal')
                                })
                                return;
                            default:
                                return;
                        }

                    }
                }
            }
            getAccessToken();
            // forceUpdate({});
        },[clientId,clientSecret,props,redirectUri])
        let newProps={
            form:form,
            isLoading:isLoading,
            isDisabled:isDisabled,
            onFinish:onFinish.bind(this),
            handleCheckPwd:handleCheckPwd.bind(this),
            thirdLogin:thirdLogin.bind(this),
            goPage:goPage.bind(this)
        }
        return (
            <WithComponent {...props}  {...newProps} />
        )
    }
}
export default hoc;


